import axios from "axios";
import qs from "qs";
import { message } from "antd";

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
});

//将params数组格式改为字符串格式
service.defaults.paramsSerializer = function (params) {
  return qs.stringify(params, { arrayFormat: "repeat", allowDots: true });
};

service.interceptors.request.use(
  (config) => {
    if (config.url !== "/user/login" && config.url !== "/user/register") {
      //从localStorage里取出token
      const token = localStorage.getItem("Access-token");
      //添加请求头
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return response.data;
    }
  },
  (error) => {
    // 统一处理错误请求
    const { response } = error;
    if (response) {
      const { status, data } = response;
      switch (status) {
        case 400:
          message.error(data.msg || "请求错误 (400)");
          break;
        case 403:
          message.error("拒绝访问 (403)");
          break;
        case 404:
          message.error("请求地址不存在 (404)");
          break;
        case 500:
          message.error("服务器内部错误 (500)");
          break;
        default:
          message.error(`请求失败，状态码：${status}`);
      }
    } else {
      // 网络错误或其他原因导致的请求失败
      message.error("网络连接异常，请稍后重试");
    }

    // 将错误返回给调用者，便于后续特定处理
    return Promise.reject(error);
  }
);

export default service;
